1 using System;
2 using UnityEngine;
3
4
5 namespace UnityStandardAssets._2D
6 {
7 public class CameraFollow : MonoBehaviour
8 {
9 public float xMargin = 1f; // Distance in the x axis the player can move before the camera follows.
10 public float yMargin = 1f; // Distance in the y axis the player can move before the camera follows.
11 public float xSmooth = 8f; // How smoothly the camera catches up with it's target movement in the x axis.
12 public float ySmooth = 8f; // How smoothly the camera catches up with it's target movement in the y axis.
13 public Vector2 maxXAndY; // The maximum x and y coordinates the camera can have.
14 public Vector2 minXAndY; // The minimum x and y coordinates the camera can have.
15
16 private Transform m_Player; // Reference to the player's transform.
17
18
19 private void Awake()
20 {
21 // Setting up the reference.
22 m_Player = GameObject.FindGameObjectWithTag("Player").transform;
23 }
24
25
26 private bool CheckXMargin()
27 {
28 // Returns true if the distance between the camera and the player in the x axis is greater than the x margin.
29 return Mathf.Abs(transform.position.x - m_Player.position.x) > xMargin;
30 }
31
32
33 private bool CheckYMargin()
34 {
35 // Returns true if the distance between the camera and the player in the y axis is greater than the y margin.
36 return Mathf.Abs(transform.position.y - m_Player.position.y) > yMargin;
37 }
38
39
40 private void Update()
41 {
42 TrackPlayer();
43 }
44
45
46 private void TrackPlayer()
47 {
48 // By default the target x and y coordinates of the camera are it's current x and y coordinates.
49 float targetX = transform.position.x;
50 float targetY = transform.position.y;
51
52 // If the player has moved beyond the x margin...
53 if (CheckXMargin())
54 {
55 // ... the target x coordinate should be a Lerp between the camera's current x position and the player's current x position.
56 targetX = Mathf.Lerp(transform.position.x, m_Player.position.x, xSmooth*Time.deltaTime);
57 }
58
59 // If the player has moved beyond the y margin...
60 if (CheckYMargin())
61 {
62 // ... the target y coordinate should be a Lerp between the camera's current y position and the player's current y position.
63 targetY = Mathf.Lerp(transform.position.y, m_Player.position.y, ySmooth*Time.deltaTime);
64 }
65
66 // The target x and y coordinates should not be larger than the maximum or smaller than the minimum.
67 targetX = Mathf.Clamp(targetX, minXAndY.x, maxXAndY.x);
68 targetY = Mathf.Clamp(targetY, minXAndY.y, maxXAndY.y);
69
70 // Set the camera's position to the target position with the same z component.
71 transform.position = new Vector3(targetX, targetY, transform.position.z);
72 }
73 }
74 }